package com.semanticweb.webapp.model.ontology;

import org.apache.lucene.document.Document;

import com.semanticweb.webapp.ontology.CIDOC;
import com.semanticweb.webapp.ontology.Ont;
import com.semanticweb.webapp.ontology.Query;
import com.semanticweb.webapp.search.IDocument;
import com.semanticweb.webapp.search.SearchMD;

/**
 * Class which represents 'Stil, skola, radionica' from the chart.
 * 
 * @author Lab
 * 
 */
public class StylePeriod extends DefaultAbstractEntity<String> implements IDocument {

    public static final String ONT_DESIGN = "design";
    public static final String ONT_PRODUCTION = "production";
    public static final String ONT_STYLE = "style";

    public StylePeriod(final String id) {
        super(id);
    }

    @Override
    public void toRDF() {
        if (this.value == null) {
            return;
        }

        final Query query = new Query();
        final String[] result = query.select("production").type("production", CIDOC.E12.queryValue())
                .type("design", CIDOC.E29.queryValue()).label("desin", this.value)
                .connect("production", CIDOC.P33.queryValue(), "design").find();

        final String itemURI = Item.formatItemURI(this.id);
        String productionURI;
        if (result == null || result.length == 0) {
            productionURI = Ont.formatURI(this.id, ONT_PRODUCTION, ONT_STYLE);
            final String designURI = Ont.formatURI(this.id, ONT_DESIGN, ONT_STYLE);

            Ont.getOntology().createIndividual(CIDOC.E12.getFullValue(), productionURI);
            Ont.getOntology().createIndividual(CIDOC.E29.getFullValue(), designURI);

            Ont.getOntology().addLabel(designURI, this.value);

            Ont.getOntology().connectIndividuals(productionURI, CIDOC.P33.getFullValue(), designURI);
        } else {
            productionURI = result[0];
        }

        Ont.getOntology().connectIndividuals(productionURI, CIDOC.P108.getFullValue(), itemURI);
    }

    public void fromRDF() {
        final String itemQueryValue = Item.formatItemQueryURI(this.id);
        final Query query = new Query();
        final String[] result = query.selectLabel().type("production", CIDOC.E12.queryValue())
                .connect("production", CIDOC.P108.queryValue(), itemQueryValue).type("design", CIDOC.E29.queryValue())
                .connect("production", CIDOC.P33.queryValue(), "design").findLabel("design");
        if (result != null && result.length > 0) {
            this.value = result[0];
        }
    }

    @Override
    public void toIndexDocument(final Document doc) {
        if (this.value != null) {
            doc.add(SearchMD.CONTENT.createField(this.value));
        }

    }
}
